import React, { useState, useEffect, useCallback } from 'react';
import * as XLSX from 'xlsx'; // 导入xlsx库
import { getProductList, deleteProducts, API_BASE_URL } from '../../Api/product';
import type { Product } from '../../types/product';
import ProductForm from './ProductForm'; // 引入表单组件
import './ProductTable.css';
import { Button, Table, Space, Popconfirm, Input, Tag, Image, Select, Card } from 'antd';
import { PlusOutlined, SearchOutlined, SyncOutlined, FileExcelOutlined, DeleteOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';

// 定义映射关系，与ProductForm中的下拉框保持一致
const teamMap: { [key: number]: string } = {
  1: '运营一部',
  2: '运营二部',
  3: '市场部',
};

const categoryMap: { [key: number]: string } = {
  1: '电子产品',
  2: '家居用品',
  3: '户外运动',
  4: '美妆个护',
};

const productTypeMap: { [key: number]: string } = {
    1: '普通商品',
    2: '捆绑商品',
    3: '变体商品',
};

const ProductTable: React.FC = () => {
  const [allProducts, setAllProducts] = useState<Product[]>([]);
  const [filteredProducts, setFilteredProducts] = useState<Product[]>([]);
  const [displayedProducts, setDisplayedProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 搜索条件state
  const [searchSku, setSearchSku] = useState('');
  const [searchProductName, setSearchProductName] = useState('');
  const [searchCategory, setSearchCategory] = useState<number | undefined>(undefined);
  const [searchTeam, setSearchTeam] = useState<number | undefined>(undefined);
  const [searchProductType, setSearchProductType] = useState<number | undefined>(undefined);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Partial<Product> | null>(null);

  const fetchProducts = useCallback(async () => {
    setLoading(true);
    try {
      const response = await getProductList({ pageIndex: 1, pageSize: 9999 });
      if (response.success) {
        const sorted = [...response.data.items].sort((a, b) => b.id - a.id);
        setAllProducts(sorted);
      } else {
        alert(response.message || '获取产品列表失败');
      }
    } catch (error) {
      console.error("获取产品列表失败:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchProducts();
  }, [fetchProducts]);

  useEffect(() => {
    const filtered = allProducts.filter(p => {
        const matchSku = !searchSku || (p.sku || '').toLowerCase().includes(searchSku.toLowerCase());
        const matchName = !searchProductName || (p.productName || p.name || '').toLowerCase().includes(searchProductName.toLowerCase());
        const matchCategory = searchCategory === undefined || String(p.categoryId) === String(searchCategory);
        const matchTeam = searchTeam === undefined || String(p.teamId) === String(searchTeam);
        const matchType = searchProductType === undefined || String(p.productTypeId) === String(searchProductType);

        return matchSku && matchName && matchCategory && matchTeam && matchType;
    });
    setFilteredProducts(filtered);
    setPagination(prev => ({ ...prev, total: filtered.length, current: 1 }));
  }, [allProducts, searchSku, searchProductName, searchCategory, searchTeam, searchProductType]);

  useEffect(() => {
    const start = (pagination.current - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    setDisplayedProducts(filteredProducts.slice(start, end));
  }, [filteredProducts, pagination.current, pagination.pageSize]);

  const handleSearch = () => {
    // 搜索逻辑已经在useEffect中处理，这里可以添加搜索反馈
    console.log('执行搜索');
  };
  
  const handleReset = () => {
    setSearchSku('');
    setSearchProductName('');
    setSearchCategory(undefined);
    setSearchTeam(undefined);
    setSearchProductType(undefined);
  };

  const handleEdit = (record: Product) => {
    setEditingProduct(record);
    setIsModalVisible(true);
  };

  const handleDelete = async (ids: React.Key[]) => {
    if (ids.length === 0) {
      alert('请选择要删除的产品');
      return;
    }

    if (window.confirm(`确定要删除选中的 ${ids.length} 个产品吗？`)) {
      setLoading(true);
      const numericIds = ids.map(id => Number(id));
      const response = await deleteProducts(numericIds);
      if (response.code === 200) {
        alert('删除成功');
        setSelectedRowKeys([]);
        fetchProducts();
      } else {
        alert(`删除失败: ${response.message}`);
      }
      setLoading(false);
    }
  };

  const handleAddProduct = () => {
    setEditingProduct(null);
    setIsModalVisible(true);
  };

  const handleExportExcel = () => {
    const dataToExport = allProducts.map(p => ({
      'ID': p.id,
      '团队': teamMap[p.teamId as number] || p.teamId,
      '产品名称': p.productName || p.name,
      'SKU': p.sku,
      '规格': p.specification,
      '类别': categoryMap[p.categoryId as number] || '未分类',
      '入库价(¥)': Number(p.purchasePrice || 0) / 100,
      '出库价(¥)': Number(p.sellingPrice || 0) / 100,
      '库存': p.stock,
    }));
    const ws = XLSX.utils.json_to_sheet(dataToExport);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '产品列表');
    XLSX.writeFile(wb, '产品列表.xlsx');
  };

  const handleModalSuccess = () => {
    setIsModalVisible(false);
    setEditingProduct(null);
    fetchProducts();
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const columns: TableProps<Product>['columns'] = [
    { 
      title: '序号', 
      key: 'index',
      width: 60,
      render: (_, __, index) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '图片',
      dataIndex: 'photo',
      key: 'photo',
      width: 80,
      render: (_, record) => {
        const imageUrl = record.photo || record.imageUrl;
        const placeholder = 'https://placehold.co/50x50/f0f0f0/999999?text=暂无';
        
        if (!imageUrl) {
          return <Image src={placeholder} width={50} />;
        }

        const fullUrl = imageUrl.startsWith('http') ? imageUrl : `${API_BASE_URL}${imageUrl}`;
        return <Image 
                  src={fullUrl} 
                  width={50} 
                  fallback={'https://placehold.co/50x50/f0f0f0/999999?text=加载失败'} 
               />;
      },
    },
    { title: '产品名称', dataIndex: 'productName', key: 'productName', width: 200 },
    { title: 'SKU', dataIndex: 'sku', key: 'sku', width: 150 },
    {
      title: '团队',
      dataIndex: 'teamId',
      key: 'teamId',
      width: 120,
      render: (id: number) => teamMap[id] || '未分配',
    },
    {
      title: '类别',
      dataIndex: 'categoryId',
      key: 'categoryId',
      width: 120,
      render: (id: number) => <Tag>{categoryMap[id] || '未分类'}</Tag>,
    },
    { title: '规格', dataIndex: 'specification', key: 'specification', width: 200 },
    { 
      title: '入库价(¥)', 
      dataIndex: 'purchasePrice', 
      key: 'purchasePrice',
      width: 120,
      render: (price: number | string) => `¥${(Number(price || 0) / 100).toFixed(2)}`,
      sorter: (a, b) => Number(a.purchasePrice || 0) - Number(b.purchasePrice || 0),
    },
    { 
      title: '出库价(¥)', 
      dataIndex: 'sellingPrice', 
      key: 'sellingPrice',
      width: 120,
      render: (price: number | string) => `¥${(Number(price || 0) / 100).toFixed(2)}`,
      sorter: (a, b) => Number(a.sellingPrice || 0) - Number(b.sellingPrice || 0),
    },
    { title: '库存', dataIndex: 'stock', key: 'stock', width: 100, sorter: (a, b) => Number(a.stock || 0) - Number(b.stock || 0) },
    { title: '库存预警', dataIndex: 'stockAlert', key: 'stockAlert', width: 100 },
    { title: '品牌', dataIndex: 'brand', key: 'brand', width: 120 },
    { title: '备注', dataIndex: 'notes', key: 'notes' },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 150,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm title="确认删除?" onConfirm={() => handleDelete([record.id])}>
            <Button type="link" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ width: '100%', padding: '0 10px' }}>
      <Card 
        style={{ width: '100%' }} 
        title="数据列表" 
        bordered={false}
        extra={
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={handleAddProduct}
            >
              新增商品
            </Button>
            <Button 
              icon={<FileExcelOutlined />} 
              onClick={handleExportExcel}
            >
              导出为Excel
            </Button>
            <Button 
              icon={<SyncOutlined />} 
              onClick={fetchProducts}
            >
              刷新数据
            </Button>
          </Space>
        }
      >
        {/* 搜索区域 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '8px' }}>
          <Space wrap>
            <Input
              placeholder="请输入SKU"
              value={searchSku}
              onChange={(e) => setSearchSku(e.target.value)}
              style={{ width: 160 }}
              allowClear
              onPressEnter={handleSearch}
            />
            <Input
              placeholder="请输入产品名称"
              value={searchProductName}
              onChange={(e) => setSearchProductName(e.target.value)}
              style={{ width: 160 }}
              allowClear
              onPressEnter={handleSearch}
            />
            <Select
              placeholder="请选择类别"
              value={searchCategory}
              onChange={setSearchCategory}
              style={{ width: 120 }}
              allowClear
            >
              {Object.entries(categoryMap).map(([id, name]) => (
                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
              ))}
            </Select>
            <Select
              placeholder="请选择团队"
              value={searchTeam}
              onChange={setSearchTeam}
              style={{ width: 120 }}
              allowClear
            >
              {Object.entries(teamMap).map(([id, name]) => (
                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
              ))}
            </Select>
            <Select
              placeholder="请选择产品类型"
              value={searchProductType}
              onChange={setSearchProductType}
              style={{ width: 140 }}
              allowClear
            >
              {Object.entries(productTypeMap).map(([id, name]) => (
                <Select.Option key={id} value={Number(id)}>{name}</Select.Option>
              ))}
            </Select>
            <Button 
              type="primary" 
              icon={<SearchOutlined />}
              onClick={handleSearch}
            >
              搜索
            </Button>
            <Button 
              icon={<SyncOutlined />} 
              onClick={handleReset}
            >
              重置
            </Button>
          </Space>
          
          {selectedRowKeys.length > 0 && (
            <Space>
              <span style={{ marginRight: 8 }}>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
              </span>
              <Popconfirm
                title={<>确定要删除选中的 {selectedRowKeys.length} 项吗?<div style={{ fontSize: '12px', color: '#999' }}>删除后数据将无法恢复，请谨慎操作！</div></>}
                onConfirm={() => handleDelete(selectedRowKeys)}
                okText="确定"
                cancelText="取消"
                okButtonProps={{ danger: true }}
              >
                <Button danger icon={<DeleteOutlined />}>
                  批量删除
                </Button>
              </Popconfirm>
            </Space>
          )}
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={displayedProducts}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showTotal: (total) => `共 ${total} 条`,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            onChange: (page, pageSize) => setPagination({ ...pagination, current: page, pageSize: pageSize }),
            onShowSizeChange: (current, size) => setPagination({ ...pagination, current: current, pageSize: size }),
            locale: {
              items_per_page: '条/页',
              jump_to: '跳至',
              jump_to_confirm: '确定',
              page: '页',
              prev_page: '上一页',
              next_page: '下一页',
              prev_5: '向前 5 页',
              next_5: '向后 5 页',
              prev_3: '向前 3 页',
              next_3: '向后 3 页'
            }
          }}
          scroll={{ x: 1800, y: 'calc(100vh - 300px)' }}
          style={{ width: '100%' }}
          bordered
          size="middle"
          rowClassName={(record, index) => index % 2 === 0 ? '' : 'table-row-alternate'}
          locale={{
            emptyText: '暂无数据',
            filterConfirm: '确定',
            filterReset: '重置',
            selectAll: '全选当页',
            selectInvert: '反选当页',
            selectionAll: '全选所有',
            sortTitle: '排序',
            triggerDesc: '点击降序',
            triggerAsc: '点击升序',
            cancelSort: '取消排序'
          }}
        />
      </Card>

      {isModalVisible && (
        <ProductForm
          visible={isModalVisible}
          onClose={() => setIsModalVisible(false)}
          onSuccess={handleModalSuccess}
          product={editingProduct}
        />
      )}
    </div>
  );
};

export default ProductTable; 